// wikiModel.go
package models

import (
	//"bytes"
	"crypto/md5"
	//"errors"
	"fmt"

	//"io/ioutil"
	"log"
	"time"

	//"xkube/common"

	//"github.com/beego/beego/v2/core/validation"

	"github.com/beego/beego/v2/client/orm"
)

type Wiki struct {
	Id         int64  `json:"id"`
	Title      string `json:"title"`
	Xcolumn    string `json:"xcolumn"`
	Sketch     string `json:"sketch"`
	Content    string `json:"content"`
	Author     string `json:"author"`
	Status     int    `json:"status"`
	Authkey    string `json:"authkey"`
	Createtime string `json:"createtime"`
	Updatetime string `json:"updatetime"`
}

func init() {
	//orm.Debug = true
	orm.RegisterModel(new(Wiki))
}

func GetList_Wiki(key, id, xcolumn string, page, page_size int64) (dps []Wiki, count int64) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Wiki))
	cond := orm.NewCondition()
	var offset int64
	if page <= 1 {
		offset = 0
	} else {
		offset = (page - 1) * page_size
	}
	if key == "column" {
		qs.Distinct().All(&dps, "Xcolumn")
		count, _ = qs.Count()
		return dps, count
	}

	if id != "" {
		cond = cond.And("id", id)
	}

	if xcolumn != "" {
		cond = cond.And("xcolumn", xcolumn)
	}

	qs = qs.SetCond(cond)
	qs.Limit(page_size, offset).OrderBy("-updatetime").All(&dps, "Id", "Title", "Xcolumn", "Sketch", "Author", "Authkey", "Status", "Createtime", "Updatetime")
	//qs.All(&xfr)
	//fmt.Println(dps)
	count, _ = qs.Count()
	var ttt = make([]Wiki, 0)
	for _, vv := range dps {
		authkey := "false"
		if vv.Authkey != "" {
			authkey = "true"
		}
		ttt = append(ttt, *&Wiki{
			Id:         vv.Id,
			Title:      vv.Title,
			Xcolumn:    vv.Xcolumn,
			Sketch:     vv.Sketch,
			Author:     vv.Author,
			Status:     vv.Status,
			Authkey:    authkey,
			Createtime: vv.Createtime,
			Updatetime: vv.Updatetime,
		})
	}
	return ttt, count
}

func Add_Wiki(u *Wiki) (int64, error) {
	o := orm.NewOrm()
	Ds := new(Wiki)
	Ds.Title = u.Title
	Ds.Xcolumn = u.Xcolumn
	Ds.Sketch = u.Sketch
	Ds.Content = u.Content
	Ds.Author = u.Author
	if u.Authkey != "" && u.Authkey != "******" {
		Ds.Authkey = fmt.Sprintf("%x", md5.Sum([]byte(u.Authkey)))
	}
	Ds.Createtime = time.Now().Format("2006-01-02 15:04:05")
	Ds.Updatetime = time.Now().Format("2006-01-02 15:04:05")
	num, err := o.Insert(Ds)
	if err != nil {
		return 0, err
	}
	return num, nil
}

func DelById_Wiki(id int64) (int64, error) {
	o := orm.NewOrm()
	status, err := o.Delete(&Wiki{Id: id})
	return status, err
}

func Edit_Wiki(id, key, value string) (int64, error) {
	o := orm.NewOrm()
	sqlstr := fmt.Sprintf("UPDATE Wiki SET %s = '%s' WHERE id = %s", key, value, id)
	res, err := o.Raw(sqlstr).Exec()
	if err == nil {
		num, _ := res.RowsAffected()
		log.Printf("[INFO] EditCluster affected nums:%d\n", num)
		return num, nil
	}
	return 0, err
}

func Update_Wiki(u *Wiki) (int64, error) {
	o := orm.NewOrm()
	op := make(orm.Params)
	op["Id"] = u.Id
	op["Title"] = u.Title
	op["Xcolumn"] = u.Xcolumn
	//op["Sketch"] = u.Sketch
	op["Content"] = u.Content
	//op["Author"] = u.Author
	if u.Authkey != "" && u.Authkey != "******" {
		op["Authkey"] = fmt.Sprintf("%x", md5.Sum([]byte(u.Authkey)))
	} else {
		op["Authkey"] = ""
	}
	op["Updatetime"] = time.Now().Format("2006-01-02 15:04:05")

	var table Wiki
	num, err := o.QueryTable(table).Filter("Id", u.Id).Update(op)

	return num, err
}

func ReadArticleById(id int64, key, authkey string) (string, error) {
	o := orm.NewOrm()
	if authkey != "" {
		authkey = fmt.Sprintf("%x", md5.Sum([]byte(authkey)))
	}
	var wk Wiki
	if key == "content" {
		err := o.Raw("SELECT content from wiki where id = ? AND authkey = ?", id, authkey).QueryRow(&wk)
		if err != nil {
			log.Printf("[ERROR] ReadArticleById Exec:%s\n", err)
			return "passwordError", err
		}
		return wk.Content, nil
	} else {
		err := o.Raw("SELECT title,author,xcolumn,authkey from wiki where id = ?", id).QueryRow(&wk)
		if err != nil {
			log.Printf("[ERROR] ReadArticleById2 Exec:%s\n", err)
			return "noFound", err
		}
		authkey := "false"
		if wk.Authkey != "" {
			authkey = "true"
		}
		return fmt.Sprintf(`{"title":"%s","author":"%s","xcolumn":"%s","authkey":"%s"}`, wk.Title, wk.Author, wk.Xcolumn, authkey), nil
	}
}

func ReadEncryCheck(id int64) string {
	o := orm.NewOrm()
	var wk Wiki
	err := o.Raw("SELECT authkey from wiki where id = ?", id).QueryRow(&wk)
	if err != nil {
		log.Printf("[ERROR] ReadArticleById Exec:%s\n", err)
		return "fail"
	}
	//log.Println(wk.Authkey)
	//log.Println(len(wk.Authkey))
	if len(wk.Authkey) > 30 {
		return "true"
	}
	return "false"
}
